import { Button, Tabs } from "antd-mobile";
import { useEffect, useState } from "react";
import { loadMedicinesAPI } from "../services/yaopinforums";
import { dalImg } from "../utils/tools";
import { Link } from "react-router-dom";
import { addToCartAPI } from "../services/cart.js";

function YaoPinTabs() {
  const [list, setList] = useState([]);
  const loadMedicines = async () => {
    const res = await loadMedicinesAPI();
    setList(res.data.list);
    console.log(res.data.list);
  };
  useEffect(() => {
    loadMedicines();
  }, []);
  const handleAddToCart = (item) => {
    console.log(item);
    addToCartAPI({ amount: 1, medicine: item.id, price: item.price }).then(
      (res) => {
        console.log(res);
        alert("成功加入购物车！");
      }
    );
  };

  return (
    <>
      <Tabs>
        <Tabs.Tab title="优选产品" key="fruits">
          {list.map((item) => (
            <div
              className="fenlei"
              key={item.id}
              style={{ display: "flex", justifyContent: "center" }}
            >
              <span
                style={{
                  textAlign: "center",
                  border: "20px solid pink",
                  borderRadius: "30%",
                }}
              >
                <h2>{item.name}</h2>
                <Link to={`/yaopin/${item.id}`}>
                  <img
                    src={dalImg(item.image)}
                    style={{
                      width: "300px",
                      height: "200px",
                      borderRadius: "10%",
                    }}
                  />
                </Link>
                <h3>{item.desc}</h3>
                <h3 style={{ color: "deeppink" }}>惊喜价：￥{item.price}</h3>
                <Button
                  color="primary"
                  shape="rounded"
                  onClick={() => {
                    handleAddToCart(item);
                  }}
                >
                  加入购物车
                </Button>
              </span>
            </div>
          ))}
          <Link to={`/wodeguanzhu`}>
            <Button
              color="primary"
              shape="rounded"
              style={{ position: "sticky", bottom: "50px", left: "270px" }}
            >
              我的购物车
            </Button>
          </Link>
        </Tabs.Tab>
      </Tabs>
    </>
  );
}
export default YaoPinTabs;
